package cn.changeforyou.web.nutz.common;

import cn.changeforyou.web.nutz.common.exception.ApiException;
import cn.changeforyou.web.nutz.common.security.AuthException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.nutz.json.Json;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionInfo;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.impl.processor.ViewProcessor;

/**
 * @author zhyu
 * @date 2021/3/9 15:55
 */
@Slf4j
public class Failchain extends ViewProcessor {

    @Override
    public void init(NutConfig config, ActionInfo ai) throws Throwable {
        view = evalView(config, ai, ai.getFailView());
    }

    @Override
    public void process(ActionContext ac) throws Throwable {
        super.process(ac);
        boolean printLog = true;
        Throwable ex = ac.getError();
        NutMap result = new NutMap();
        HttpServletResponse response = ac.getResponse();
        if (ex instanceof ValidationException) {
            result.setv("status", 401);
            result.setv("message", ex.getMessage());
            response.setStatus(500);
            printLog = false;
        } else if (ex instanceof ApiException) {
            printLog = false;
            result.setv("status", -1);
            result.setv("error", ex.getMessage());
        } else if (ex instanceof AuthException) {
            result.setv("status", -1);
            result.setv("message", ex.getMessage());
            response.setStatus(403);
        } else {
            result.setv("status", -1);
            result.setv("message", "服务器异常");
            response.setStatus(500);
        }
        byte[] dataByteArr = Json.toJson(result).getBytes("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(dataByteArr);
        if (printLog && log.isWarnEnabled()) {
            String uri = Mvcs.getRequestPath(ac.getRequest());
            log.warn(String.format("Error@%s :", uri), ac.getError());
        }

    }
}
